package dataSaving;

import java.io.*;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import data.*;
import dataSaving.PMF;

/**
 * Simple demonstration for an Applet <-> Servlet communication.
 */
public class TestSerializingServlet extends HttpServlet {
	/**
	 * Get a String-object from the applet and send it back.
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			response.setContentType("application/x-java-serialized-object");

			// read a String-object from applet
			// instead of a String-object, you can transmit any object, which
			// is known to the servlet and to the applet
			InputStream in = request.getInputStream();
			ObjectInputStream inputFromApplet = new ObjectInputStream(in);
			Object echo1 = inputFromApplet.readObject();
			// Object echo2 = inputFromApplet.readObject();

			PersistenceManager pm = PMF.get().getPersistenceManager();
			try {
				pm.makePersistent(echo1);
				// pm.makePersistent(echo2);

				String query = "select from " + Course.class.getName();
				List<Course> list = (List<Course>) pm.newQuery(query).execute();

				// echo it to the applet
				OutputStream outstr = response.getOutputStream();
				ObjectOutputStream oos = new ObjectOutputStream(outstr);
				for (Course l : list) {
					oos.writeObject(l);
					System.out.println("ff");
				}
				System.out.println("ff");
				// oos.writeObject(echo1);
				// oos.writeObject(echo2);
				oos.flush();
				oos.close();

			} finally {
				pm.close();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
